package com.cyzy.service;

import com.cyzy.dto.ClassDO;
import com.cyzy.dto.User;
import com.cyzy.dto.UserSignIn;
import com.cyzy.mapper.CameraMapper;
import com.cyzy.util.Base64Util;
import com.cyzy.util.FaceMatchUtil;
import com.cyzy.util.HttpUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CameraService {

    @Autowired
    private FaceMatchUtil faceMatchUtil;

    @Autowired
    private CameraMapper cameraMapper;

    //人脸对比
    public double compareFaceImages(MultipartFile image1, MultipartFile image2) throws IOException {
        // 创建临时文件来保存上传的图片
        String image1Path = saveToFile(image1);
        String image2Path = saveToFile(image2);

        String result = faceMatchUtil.faceMatch(image1Path, image2Path);

        // 创建ObjectMapper实例
        ObjectMapper objectMapper = new ObjectMapper();

        // 解析JSON字符串为JsonNode对象
        JsonNode rootNode = objectMapper.readTree(result);

        // 提取result节点下的score值
        double score = rootNode.path("result").path("score").asDouble();
        // 清理临时文件
        java.nio.file.Files.deleteIfExists(java.nio.file.Paths.get(image1Path));
        java.nio.file.Files.deleteIfExists(java.nio.file.Paths.get(image2Path));
        return score;
    }

    //人脸比对
    public double compareFaceUserId(MultipartFile image, String userId) throws IOException {
        String imagePath = saveToFile(image);

        String result = faceMatchUtil.faceSearch(imagePath, "1", userId);
        System.out.println(result);
        // 1. 创建 Gson 实例
        Gson gson = new Gson();

        // 2. 将 JSON 字符串解析为 JsonObject（根节点）
        JsonObject rootObj = gson.fromJson(result, JsonObject.class);
        JsonObject resultObj = rootObj.getAsJsonObject("result"); // 获取 result 节点
        JsonArray userListArr = resultObj.getAsJsonArray("user_list"); // 获取 user_list 数组
        JsonObject firstUserObj = userListArr.get(0).getAsJsonObject(); // 数组第1个元素
        double score = firstUserObj.get("score").getAsDouble(); // 提取 score 并转为 double
        java.nio.file.Files.deleteIfExists(java.nio.file.Paths.get(imagePath));
        return score;
    }
    //人脸注册
    public String addFace(MultipartFile image, String userId) throws IOException {
        String imagePath = saveToFile(image);
        System.out.println(userId+"userid");
        String result = faceMatchUtil.add(imagePath, "1", userId);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(result);
        String faceToken = null;
        // 提取 face_token（注意先判断节点是否存在，避免空指针）
        if (rootNode.has("result")) {
            JsonNode resultNode = rootNode.get("result");
            if (resultNode.has("face_token")) {
                faceToken = resultNode.get("face_token").asText();
                cameraMapper.addFace(userId, faceToken);
                System.out.println(faceToken); // 输出：80a969e13e80768307044f8160da47eb
            }
        }
        java.nio.file.Files.deleteIfExists(java.nio.file.Paths.get(imagePath));

        return faceToken;
    }
    //查看签到记录
    public List<User> getUserSignIn(String liveName){
        return cameraMapper.getUserSignIn(liveName);
    }
    //修改签到记录
    public int updateUserSignIn(String userId, int statues,String liveName){
        return cameraMapper.updateUserSignIn(userId, statues,liveName);
    }
    //获取所有班级
    public List<ClassDO> getAllClass(){
        return cameraMapper.getAllClass();
    }

    //获取所有学生
    public List<User> getAllStudents(String classId,String liveName){

        List<User> allStudents = cameraMapper.getAllStudents(classId);
        for (User allStudent : allStudents) {
            cameraMapper.addUserSignOut(String.valueOf(allStudent.getId()), classId, liveName);
        }
        return allStudents;
    }

    /**
     * 将MultipartFile保存为临时文件并返回文件路径
     * @param multipartFile 上传的文件
     * @return 临时文件路径
     * @throws IOException IO异常
     */
    private String saveToFile(MultipartFile multipartFile) throws IOException {
        // 创建临时文件
        java.nio.file.Path tempFile = java.nio.file.Files.createTempFile("face-", ".tmp");
        multipartFile.transferTo(tempFile);
        return tempFile.toString();
    }

}
